<template>
  <n-data-table
      remote
      :max-height="590"
      :columns="columns"
      :data="pageResult.data"
      :loading="loading"
      :pagination="pagination"
      :row-key="rowKey"
      @update:page="handlePageChange"
      @update:pageSize="handlePageSizeChange"
  />
</template>

<script lang="ts" setup>
import {reactive, computed} from "vue";
import {DataTableColumn, PaginationInfo} from "naive-ui";
import {PageResult} from "../../model/Common";

const props = defineProps<{
  columns: Array<DataTableColumn>,
  pageResult: PageResult<Object>,
  loading: boolean
}>();

const emits = defineEmits<{
  (e: "handlePageQuery", page?: number, size?: number): void
}>();

const pagination = reactive({
  page: computed(() => props.pageResult.page),
  pageCount: computed((): number => {
    return props.pageResult.total % pagination.pageSize === 0
        ? ~~(props.pageResult.total / pagination.pageSize)
        : ~~(props.pageResult.total / pagination.pageSize) + 1
  }),
  pageSize: 10,
  itemCount: computed(() => props.pageResult.total),
  showSizePicker: true,
  pageSizes: [10, 20, 50, 100],
  prefix: ({itemCount}: PaginationInfo) => {
    return `共${itemCount}条`;
  }

});

const handlePageChange = (page: number): void => {
  handleQuery(page);
}

const handlePageSizeChange = (size: number): void => {
  handleQuery(undefined, size);
}

const handleQuery = (page = pagination.page, size = pagination.pageSize): void => {
  pagination.pageSize = size;
  emits("handlePageQuery", page, size);
}

const rowKey = (rowData: { id: bigint }) => {
  return rowData.id;
}

</script>
